package com.wenjh.jdmzt.android.synctask;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

import com.wenjh.jdmzt.AndroidKit;
import com.wenjh.jdmzt.protocol.HttpClient;
import com.wenjh.jdmzt.service.model.Image;
import com.wenjh.jdmzt.util.Log4Android;

@SuppressLint("NewApi")
public class LoadImageTask extends CallbackTask<Bitmap> {
	Image image = null;
	File file = null;
	private Log4Android log = new Log4Android(this);
	private static ThreadPool localThreadPoll = new ThreadPool(10, 10);
	private static ThreadPool g3NetThreadPoll = new ThreadPool(1, 2);
	private static ThreadPool wifiNetThreadPoll = new ThreadPool(3, 5);
	private ProgessCallback progessCallback = null;
	
	/**
	 * 加载图片，优先加载本地缓存图，如果找不到此图就从网上下载，下载完成后缓存起来供下次使用。
	 * @param image
	 */
	public LoadImageTask(Image image) {
		this.image = image;
		File dir = new File(AndroidKit.getApp().getExternalCacheDir(), image.getImageId().substring(0, 1));
		if(!dir.exists()) {
			dir.mkdirs();
		}
		file = new File(dir, image.getImageId());
	}
	
	public void setProgessCallback(ProgessCallback progessCallback) {
		this.progessCallback = progessCallback;
	}
	
	public ProgessCallback getProgessCallback() {
		return progessCallback;
	}
	
	public static void clear() {
		localThreadPoll.getQueue().clear();
		g3NetThreadPoll.getQueue().clear();
		wifiNetThreadPoll.getQueue().clear();
	}
	
	@Override
	public void run() {
		Bitmap bitmap = null;
		try {
			if(isLocalExists()) {
				bitmap = loadLocalImage(file, progessCallback);
			}
			if(bitmap == null) {
				HttpClient.saveFile(image.getUrlString(), file, progessCallback);
				bitmap = loadLocalImage(file, null);
			}
		} catch (Throwable e) {
			log.e(e);
			if(progessCallback != null) {
				progessCallback.onProgessChanged(-1, -1);
			}
		} finally {
			callBack(bitmap);
		}
	}
	
	public static Bitmap loadLocalImage(Image image) throws IOException {
		File dir = new File(AndroidKit.getApp().getExternalCacheDir(), image.getImageId().substring(0, 1));
		if(!dir.exists()) {
			return null;
		}
		
		File imageFile = new File(dir, image.getImageId());
		if(!imageFile.exists()) {
			return null;
		}
		
		return loadLocalImage(imageFile, null);
	}
	
	public void execute() {
		log.i(file.getPath()+", exists="+file.exists());
		if(file.exists()) {
			localThreadPoll.execute(this);
		} else if(AndroidKit.isWifi()) {
			wifiNetThreadPoll.execute(this);
		} else {
			g3NetThreadPoll.execute(this);
		}
	}
	
	public boolean isLocalExists() {
		return file.exists();
	}
	
	public static Bitmap loadLocalImage(File imageFile, ProgessCallback callback) throws IOException {
		if(!imageFile.exists()) {
			return null;
		}
		Log4Android log = new Log4Android("loadLocalImage");
		log.i(imageFile.getPath());
		
		if(callback != null) {
			callback.onProgessChanged(-2, -2);
		}
	
		InputStream is = null;
		Bitmap bitmap = null;
		try {
			Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;

			while (true) {
				is = new FileInputStream(imageFile);
				bitmap = BitmapFactory.decodeStream(is, null, options);
				if (!options.inJustDecodeBounds) {
					break;
				}

//				int maxWidth = 0;
//				int maxHeight = 0;
//				if(smaller) {
//					maxWidth = 100;
//					maxHeight = 100;
//				} else {
//					maxWidth = 1024;
//					maxHeight = 1024;
//				}
				int maxWidth = 1024;
				int maxHeight = 1024;
				
				boolean scaleByHeight = Math.abs(options.outHeight - maxHeight) >= Math
						.abs(options.outWidth - maxWidth);

				options.inJustDecodeBounds = false;

				/*
				 * 面积大于所规定的最大Size，则需要缩放原图（目的是为了避免载入一张过大的图，内存溢出）
				 */
				if (options.outHeight * options.outWidth >= maxWidth * maxHeight) {
					double sampleSize = scaleByHeight ? options.outHeight
							/ maxHeight : options.outWidth / maxWidth;
					options.inSampleSize = (int)sampleSize;
				}

				is.close();
			}

			return bitmap;
		} catch (IOException e) {
			throw e;
		} finally {
			log.i(imageFile.getPath()+"--------------------end");
			if(callback != null) {
				callback.onProgessChanged(0, 0);
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException ignored) {
				}
			}
		}
	}
	
}
